<?php

namespace App\Models;

use App\Libraries\Common\CommonFun;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class RsMsginfo extends Model
{
    use HasFactory;

    protected $table='rs_msginfo';
    public $timestamps=false;

    //查询数据
    public static function list($page = 1, $limit = 20, $params = []){
        $ary_where = array();
        $msg_title=data_get($params,'msg_title',false);

        if($msg_title){
            $ary_where[] = ['msg_title', 'like', '%'.$msg_title.'%'];
        }
        $query = self::where($ary_where);
        $count = $query->count();
        $data = $query->offset(CommonFun::getOffset($page, $limit))->limit($limit)->orderBy('id', 'desc')->get()->map(function (RsMsginfo $rebate) use ($count) {
            $rebate = $rebate->attributesToArray();
            $rebate['getSend']=User::where(['id'=>$rebate['send_id']])->first()->toArray();
            $rebate['getRecevier']=User::where(['id'=>$rebate['recevier_id']])->first()->toArray();

            $rebate['msg_type_name']=RsMsgManage::where(['id'=>$rebate['msg_type_id']])->first()->toArray();
            $rebate['is_read'] = $rebate['is_read']==0 ?'未读' : '已读';

            return $rebate;
        })->toArray();

        return $data ? compact('count', 'data') : false;
    }


    //查询发送人信息
    public function getSend(){
        return $this->hasOne(User::class,'id','send_id');
    }
    //查询接收人信息
    public function getRecevier(){
        return $this->hasOne(User::class,'id','recevier_id');

    }
    //获取类型名称
    public function getRsManage(){
        return $this->hasOne(RsMsgManage::class ,'id','msg_type_id');
    }

    //数据添加参数
    public static function msgCreated($data){
        $model=new self();
        $model->msg_type_id=$data['msg_type_id'];
        $model->msg_title=$data['msg_title'];
        $model->msg_content=$data['msg_content'];
        $model->send_id=$data['send_id'];
        $model->recevier_id=$data['recevier_id'];
        $model->send_date=isset($data['send_date'])?$data['send_date']:Carbon::now();
        $req=$model->save();
        Log::info($req);
        if($req){
            return true;
        }else{
            return false;
        }

    }

}
